<?php
/**
 * Copyright (c) 2018,2345
 * 摘    要：User controller
 * 作    者：林幸亿
 * 修改日期：2018.05.09
 */

namespace App\Controllers;

use \Core\View;
use \App\Models\Account;
use \App\Models\User;
use \Library\MysqlDb;
use \Library\Session;
use \Library\Paginator;
use \Library\UIHelper;

class UserController extends \Core\Controller
{
    private $model;
    private $view;
    private $session;
    
    /**
     * 功    能：Check if user is authenticated before proceeding
     * 修改日期：2018-4-18
     */
    public function __construct()
    {
        $this->session = Session::getInstance();
        // Set to true if using https
        $this->session->start_session('_s', false);
        //die(var_dump($_SESSION));
//session_start();
        //Load the model
        $this->model = new User();
        $account = new Account();

        if($account->checkAuth() == false) {
            //Set the  flash message with default class
            $this->session->flash('loginMsg',
			'<div class="alert alert-danger alert-dismissible fade show" role="alert">您没有权限访问此页面，请登录。 <br>
			You are not authorized to access this page, please login.
			<button type="button" class="close" data-dismiss="alert" aria-label="Close">
				<span aria-hidden="true">&times;</span>
			</button>
			</div>', 'alert alert-danger');
            header("Location: " . BASE_URL . '/login');
        }
    }

    function __destruct()
    {
    }
    
    /**
     * 功    能：Call the User model and display the header view
     * 修改日期：2018-05-08
     */   
    protected function before()
    {
        $this->view = View::renderTpl();
		$this->view->assign('menuLink', UIHelper::generateMenu(LINKS));
		$this->view->assign('accountLink', UIHelper::accountLink());
        $this->view->display('Layout/header.tpl.html');
    }

    /**
     * 功    能：Display the footer view
     * 修改日期：2018-4-18
     */    
    protected function after()
    {
        $this->view->display('Layout/footer.tpl.html');
    }
    
    /**
     * 功    能：Show the index page
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function indexAction()
    {
    }
    
    /**
     * 功    能：Get all the users and show in the paginated table
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function usersAction()
    {
        $db = MysqlDb::getInstance();
        $sql = 'SELECT id, name, email, mobile FROM contacts'; //ORDER BY id DESC

        $Paginator = new Paginator($db, $sql);
                    
        $limit = ( isset($_GET['limit']) ) ? $_GET['limit'] : 10;
        $page = ( isset($_GET['page']) ) ? $_GET['page'] : 1;
        $links = ( isset($_GET['links']) ) ? $_GET['links'] : 15;

        $results = $Paginator->getData($page, $limit);

        $pagerDisplay = $Paginator->createLinks($links, 'pagination justify-content-md-center');
        //var_dump($results->data); 
        //die('end');
        //$user = User::getAll();
        //print_r($user);
        $this->view->assign('listMsg', $this->session->flash('listMsg'));
        $this->view->assign('pager', $pagerDisplay);
        $this->view->assign('arrData', $results->data);
        $this->view->display('User/list.tpl.html');

    }

    /**
     * 功    能：Show the create user page
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function createAction()
    {
        $this->view->display('User/create.tpl.html');
    }
    
    /**
     * 功    能：Create a user in the database
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function createPost()
    {
        if (! empty($_POST))
        {
            // keep track validation errors
            $nameError = null;
            $emailError = null;
            $mobileError = null;

            // keep track post values
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];

            // Validate input
            $valid = true;
            if (empty($name))
            {
                $nameError = '请输入名称<br>Please enter Name';
                $valid = false;
            }

            if (empty($email))
            {
                $emailError = '请输入名称<br>Please enter Email Address';
                $valid = false;
            }
            else if (! filter_var($email, FILTER_VALIDATE_EMAIL))
            {
                $emailError = '请输入有效的电子邮件<br>Please enter a valid Email Address';
                $valid = false;
            }

            if (empty($mobile))
            {
                $mobileError = '请输入手机号码<br>Please enter Mobile Number';
                $valid = false;
            }

            // Update data if validation is successful and redirect to main page
            if ($valid)
            {
                $user = ['name'=>$name, 'email'=>$email, 'mobile'=>$mobile];
                $insertId = $this->model->insert($user);
                //die(var_dump($insertId));
                if($insertId)
                {
                    //Redirect back to main page
                    header("Location: " . BASE_URL . '/users');
                }
                else
                {
                    header("Location: " . BASE_URL . '/user/create/');
                }
            }
        }
    }

    /**
     * 功    能：Get a user from the database
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function userAction($id=null)
    {
        $user = $this->model->getOne($id);
        $this->view->assign('userName', $user['name']);
        $this->view->assign('userEmail', $user['email']);
        $this->view->assign('userMobile', $user['mobile']);
        $this->view->display('User/user.tpl.html');
    }
    
    /**
     * 功    能：Show the User Update page
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function updateAction($id=null)
    {
        $user = $this->model->getOne($id);
        $this->view->assign('userId', $user['id']);
        $this->view->assign('userName', $user['name']);
        $this->view->assign('userEmail', $user['email']);
        $this->view->assign('userMobile', $user['mobile']);
        $this->view->display('User/update.tpl.html');
    }
    
    /**
     * 功    能：Update a user in the database
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function updatePost()
    {
        if (! empty($_POST))
        {
            // keep track validation errors
            $nameError = null;
            $emailError = null;
            $mobileError = null;

            // keep track post values
            $id = $_POST['id'];
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];

            // Validate input
            $valid = true;
            if (empty($name))
            {
                $nameError = '请输入名称<br>Please enter Name';
                $valid = false;
            }

            if (empty($email))
            {
                $emailError = '请输入名称<br>Please enter Email Address';
                $valid = false;
            }
            else if (! filter_var($email, FILTER_VALIDATE_EMAIL))
            {
                $emailError = '请输入有效的电子邮件<br>Please enter a valid Email Address';
                $valid = false;
            }

            if (empty($mobile))
            {
                $mobileError = '请输入手机号码<br>Please enter Mobile Number';
                $valid = false;
            }

            // Update data if validation is successful and redirect to main page
            if ($valid)
            {
                $user = ['name'=>$name, 'email'=>$email, 'mobile'=>$mobile];
                $count = $this->model->update($id, $user);
                
                if($count > 0)
                {
                    //Redirect back to main page
                    header("Location: " . BASE_URL . '/users');
                }
                else
                {
                    header("Location: " . BASE_URL . '/user/update/' . $id);
                }
            }
        }
        
        die("<p>No Direct Script Access</p>");
    }

    /**
     * 功    能：Show the User Delete page
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function deleteAction($id=null)
    {
        $user = $this->model->getOne($id);
        $this->view->assign('userName', $user['name']);
        $this->view->assign('userEmail', $user['email']);
        $this->view->assign('userMobile', $user['mobile']);
        
        $this->view->assign('userId', $id);
        $this->view->display('User/delete.tpl.html');
    }

    /**
     * 功    能：Delete the user from the database
     *
     * @return void
     * 修改日期：2018-4-18
     */
    public function deletePost()
    {
        if (! empty($_POST))
        {
            // keep track post values
            $id = $_POST['id'];
            $count = $this->model->delete($id);
                
            if($count > 0)
            {
				$this->session->flash('listMsg', '<div class="alert alert-success alert-dismissible fade show" role="alert">User has been deleted successfully.
						<button type="button" class="close" data-dismiss="alert" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>');
					
                //Redirect back to main page
                header("Location: " . BASE_URL . '/users');
            }
            else
            {
                header("Location: " . BASE_URL . '/user/delete/' . $id);
            }
        }
    }

}
